//
//  HZPeiziBuySellVC.m
//  Stock_Stategy
//
//  Created by MayerF on 2017/11/29.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "HZPeiziBuySellVC.h"
#import "HZPeiziBuySellView.h"
#import "HZSearchTool.h"
#import "HZNetworkTool.h"
#import "MYHttp.h"
#import "MYStockAlertViewController.h"

@interface HZPeiziBuySellVC ()
{
    int _nMinPriceId;
}
@property (nonatomic, strong)HZPeiziBuySellView *pBuySellView;
@property (nonatomic, assign)NSInteger nType;// 1:买入，2：卖出
@property (nonatomic, copy)NSString *pCode;
@end

@implementation HZPeiziBuySellVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//    self.title = @"买卖";
    
    //关联逻辑管理对象
    self.logicManager = [HZBaseLogjcManager new];
    self.view.logicManager = self.logicManager;
    
    _pBuySellView = [HZPeiziBuySellView new];
    [self.view addSubview:_pBuySellView];
    [_pBuySellView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    [self p_registerBlock];
    
    if ([self.params.allKeys containsObject:@"type"]) {
        NSNumber *type = self.params[@"type"];
        _nType = [type integerValue];
    }
    if ([self.params.allKeys containsObject:@"code"]) {
        _pCode = self.params[@"code"];
    }
    
    if (_nType == 1) {
        self.title = @"买入";
        [_pBuySellView setBuySellType:kTrade_Buy_Type];
    }else {
        self.title = @"卖出";
        [_pBuySellView setBuySellType:kTrade_Sell_Type];
    }
    if (_pCode && ![_pCode isEqual:@""]) {
        [self updateMinPriceWithCode:_pCode];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [HZNetworkTool networkCacelSubscribeId:_nMinPriceId];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self p_requestTradeList];
}

- (void)showMoreTradeTypeWithBtn:(id)other
{
    UIButton *btn = other[0];
    NSInteger nMarket = [other[1] integerValue];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请选择申报方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    void (^handler)(UIAlertAction *) = ^(UIAlertAction *action){
        [btn setTitle:action.title forState:UIControlStateSelected];
        [self dismissViewControllerAnimated:YES completion:nil];
    };
    
    if (nMarket == 1) {// 上海
        UIAlertAction *account = [UIAlertAction actionWithTitle:@"限价" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account];
        UIAlertAction *account4 = [UIAlertAction actionWithTitle:@"五档即成剩撤" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account4];
        UIAlertAction *account5 = [UIAlertAction actionWithTitle:@"五档即成剩转限" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account5];
    }else if (nMarket == 2) {
        UIAlertAction *account = [UIAlertAction actionWithTitle:@"限价" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account];
        UIAlertAction *account2 = [UIAlertAction actionWithTitle:@"对方最优" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account2];
        UIAlertAction *account3 = [UIAlertAction actionWithTitle:@"本方最优" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account3];
        UIAlertAction *account4 = [UIAlertAction actionWithTitle:@"即成剩撤" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account4];
        UIAlertAction *account5 = [UIAlertAction actionWithTitle:@"五档即成剩撤" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account5];
        UIAlertAction *account6 = [UIAlertAction actionWithTitle:@"全成或撤销" style:UIAlertActionStyleDefault handler:handler];
        [alertVC addAction:account6];
    }
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alertVC addAction:cancel];
    [self presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark -
#pragma mark blockAction
- (void)p_registerBlock
{
    __weak typeof (self)weakSelf = self;
    [self.logicManager mapLogic:kLogicRouterPeiziTradeType toBlock:^id(NSDictionary *params, id other) {
        [weakSelf showMoreTradeTypeWithBtn:other];
        return nil;
    }];
    [self.logicManager mapLogic:kLogicRouterPeiziCodeSearch toBlock:^id(NSDictionary *params, id other) {
        [weakSelf updateMinPriceWithCode:other];
        return nil;
    }];
    [self.logicManager mapLogic:kLogicRouterPeiziCancelSubscribe toBlock:^id(NSDictionary *params, id other) {
        [HZNetworkTool networkCacelSubscribeId:_nMinPriceId];
        return nil;
    }];
    [self.logicManager mapLogic:kLogicRouterPeiziBuySellAction toBlock:^id(NSDictionary *params, id other) {
        [weakSelf p_showGoBuySellWithParams:other];
        return nil;
    }];
}

- (void)p_showGoBuySellWithParams:(NSArray *)params
{
    if (params.count != 7) { return;}
    NSString *type = params[0];
    NSString *name = params[1];
    NSString *code = params[2];
    NSString *price = params[4];
    NSString *num = params[5];
    NSString *flag = params[6];
    
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:4];
    MYStockAlertModel *model1 = [MYStockAlertModel new];
    model1.model_left = @"股票名称:";
    model1.model_right = name;
    MYStockAlertModel *model2 = [MYStockAlertModel new];
    model2.model_left = @"股票代码:";
    model2.model_right = code;
    MYStockAlertModel *model3 = [MYStockAlertModel new];
    model3.model_left = @"委托方向:";
    model3.model_right = flag;
    MYStockAlertModel *model4 = [MYStockAlertModel new];
    model4.model_left = @"申报方式:";
    model4.model_right = type;
    MYStockAlertModel *model5 = [MYStockAlertModel new];
    model5.model_left = @"委托价格:";
    model5.model_right = price;
    MYStockAlertModel *model6 = [MYStockAlertModel new];
    model6.model_left = @"委托数量:";
    model6.model_right = num;
    [tempArray addObject:model1];
    [tempArray addObject:model2];
    [tempArray addObject:model3];
    [tempArray addObject:model4];
    [tempArray addObject:model5];
    [tempArray addObject:model6];
    
    MYStockAlertViewController *alertVC = [MYStockAlertViewController alertControllerWithTitle:@"提示" message:nil data:tempArray];
    [alertVC addOkAction:^(id result) {
        [self p_requestTradeWithParams:params];
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
    [alertVC addCancelAction:nil];
    [self presentViewController:alertVC animated:NO completion:nil];
}

- (void)updateMinPriceWithCode:(NSString *)code
{
    __weak typeof (self)weakSelf = self;
    [HZSearchTool searchStockDictWithSearchInfo:code success:^(NSArray *result) {
        if (result.count == 0) { return;}
        MYSearchResultModel *searchModel = result[0];
        _nMinPriceId = [HZNetworkTool networkSubscribeDataWithapiType:kHZApi_MinPrice_Type code:searchModel.m_stockCode market:searchModel.n_TradeId success:^(id model, kHZApiType apiType) {
            [weakSelf.pBuySellView updateTopData:model];
            [weakSelf getInfoParamsWithModel:model];
        }];
    }];
}
- (void)getInfoParamsWithModel:(HZMinPriceModel *)model
{
    NSString *price = @"";
    NSArray *wudang = model.model_wuDangArray;
    if (_nType == 1 && wudang.count > 4) {
        HZWuDangModel *model = wudang[4];
        price = model.model_price;
    }else if (_nType == 2 && wudang.count > 5) {
        HZWuDangModel *model = wudang[5];
        price = model.model_price;
    }
    [self p_requestInfoWithPrice:price code:model.model_code];
}
- (void)p_requestTradeList
{
    [SVProgressHUD show];
    
    NSArray *array = @[@{@"funcid":@"4", @"session":[HZUserManager manager].peiziAccountSession}];
    [MYHttp post:kAPIPeiziHost params:array success:^(id response) {
        NSMutableArray *tempArray = [NSMutableArray array];
        if ([response isKindOfClass:[NSArray class]]) {
            NSArray *array = (NSArray *)response;
            for (NSDictionary *dict in array) {
                HZPeiziTradeStockListModel *model = [HZPeiziTradeStockListModel mj_objectWithKeyValues:dict];
                [tempArray addObject:model];
            }
        }
        [_pBuySellView updateAccountData:tempArray];
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}
- (void)p_requestTradeWithParams:(NSArray *)params
{
    NSString *type = params[0];
//    NSString *name = params[1];
    NSString *code = params[2];
    NSString *market = params[3];
    NSString *price = params[4];
    NSString *num = params[5];
    NSString *flag = params[6];
    NSString *warning = @"";
    if ([type isEqual:@"限价"]) {
        type = @"0";
    }else if ([type isEqual:@"对方最优"]) {
        type = @"1";
    }else if ([type isEqual:@"本方最优"]) {
        type = @"3";
    }else if ([type isEqual:@"即成剩撤"]) {
        type = @"4";
    }else if ([type isEqual:@"五档即成剩撤"]) {
        type = @"5";
    }else if ([type isEqual:@"五档即成剩转限"]) {
        type = @"2";
    }else if ([type isEqual:@"全成或撤销"]) {
        type = @"6";
    }
    if ([flag isEqual:@"买入"]) {
        flag = @"B";
        warning = @"买入委托提交成功";
    }else if ([flag isEqual:@"卖出"]) {
        flag = @"S";
        warning = @"卖出委托提交成功";
    }
    
    [SVProgressHUD show];
    NSArray *array = @[@{@"funcid":@"10", @"session":[HZUserManager manager].peiziAccountSession,
                         @"ordertype": type,
                         @"stkcode": code,
                         @"bstype": flag,
                         @"ordercount": num,
                         @"price": price,
                         @"market": market
                         }];
    [MYHttp post:kAPIPeiziHost params:array success:^(id response) {
        [_pBuySellView clearBothData];
        [SVProgressHUD showSuccessWithStatus:warning];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self p_requestTradeList];
        });
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}
- (void)p_requestInfoWithPrice:(NSString *)price
                          code:(NSString *)code
{
    NSString *type = @"";
    if (_nType == 1) {
        type = @"B";
    }else {
        type = @"S";
    }
    NSArray *array = @[@{@"funcid":@"8", @"session":[HZUserManager manager].peiziAccountSession,
                         @"bstype": type,
                         @"price": price,
                         @"stkcode": code
                         }];
    [MYHttp post:kAPIPeiziHost params:array success:^(id response) {
        NSString *maxNum = @"0";
        if ([response isKindOfClass:[NSArray class]]) {
            NSArray *array = (NSArray *)response;
            for (NSDictionary *dict in array) {
                maxNum = [NSString stringWithFormat:@"%ld", [dict[@"max_qty"] integerValue]];
            }
        }
        [_pBuySellView updateMoneyData:maxNum];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}

@end
